import { websiteKeywordsApi } from "@/api/esArticle";
import { useGetWebsiteDomains } from "@/hooks/useCommon";
import { useVModels } from "@vueuse/core";
import { Divider, InputNumber, Modal, Select, Space, Textarea, message } from "ant-design-vue";

// 修改或添加的组件
export const KeywordDensityAddOrUpdateComponent = defineComponent({
    props: ["visible", "currentRow"],
    setup(props: { visible: boolean; currentRow: WebsiteKeywordsTableRow }, { emit }) {
        const { visible, currentRow } = useVModels(props, emit);
        const isAdd = computed(() => !currentRow.value);
        const pcDomain = ref("");
        const webid = ref(0);
        const relatedWords = ref("");
        const subject = ref("");
        const longTailedWord = ref("");
        const relatedWordsRatio = ref(2);
        const subjectRatio = ref(3);
        const longTailedWordRatio = ref(2);
        watch(
            () => currentRow.value,
            () => {
                if (visible.value && currentRow.value) {
                    const {
                        subject: rowSubject,
                        long_tailed_word: rowLongtailedWord,
                        related_words: rowRelatedWords
                    } = currentRow.value;
                    // 基本信息初始化
                    pcDomain.value = currentRow.value.pc_domain;
                    webid.value = currentRow.value.webid;
                    // @ts-ignore
                    subject.value = rowSubject.keywords.map((item) => item.keyword).join("\n");
                    // @ts-ignore
                    longTailedWord.value = rowLongtailedWord.keywords.map((item) => item.keyword).join("\n");
                    // @ts-ignore
                    relatedWords.value = rowRelatedWords.keywords.map((item) => item.keyword).join("\n");
                    // 密度值 初始化
                    relatedWordsRatio.value = rowRelatedWords.ratio;
                    subjectRatio.value = rowSubject.ratio;
                    longTailedWordRatio.value = rowLongtailedWord.ratio;
                }
            }
        );
        const { websiteOptions, websiteMap } = useGetWebsiteDomains();
        const onChange = () => {
            webid.value = websiteMap.value[pcDomain.value];
        };
        const ok = () => {
            if (!pcDomain.value || !webid.value) {
                return message.error("请选择域名!");
            }
            // 拆分关键词 过滤空值
            const long_tailed_word = Array.from(
                new Set(
                    longTailedWord.value
                        .split("\n")
                        .map((v) => v.trim())
                        .filter(Boolean)
                )
            );
            const subject_ = Array.from(
                new Set(
                    subject.value
                        .split("\n")
                        .map((v) => v.trim())
                        .filter(Boolean)
                )
            );
            const related_words = Array.from(
                new Set(
                    relatedWords.value
                        .split("\n")
                        .map((v) => v.trim())
                        .filter(Boolean)
                )
            );
            // 包装词
            const subjectKeywords = subject_.map((item) => ({ keyword: item, density: 0.0 }));
            const longTailedWordKeywords = long_tailed_word.map((item) => ({ keyword: item, density: 0.0 }));
            const relatedWordsKeywords = related_words.map((item) => ({ keyword: item, density: 0.0 }));

            const commonObj = {
                subject: { keywords: subjectKeywords, ratio: subjectRatio.value },
                long_tailed_word: { keywords: longTailedWordKeywords, ratio: longTailedWordRatio.value },
                related_words: { keywords: relatedWordsKeywords, ratio: relatedWordsRatio.value }
            };

            if (isAdd.value) {
                websiteKeywordsApi("post", {
                    pc_domain: pcDomain.value,
                    webid: webid.value,
                    ...commonObj
                })
                    .then(commonSuccessCallback)
                    .catch(commonErrorCallback)
                    .finally(commonFinallyCallback);
            } else {
                websiteKeywordsApi("put", {
                    id: currentRow.value.id,
                    ...commonObj
                })
                    .then(commonSuccessCallback)
                    .catch(commonErrorCallback)
                    .finally(commonFinallyCallback);
            }
        };
        const isReloadData = inject("isReloadData") as Ref<boolean>;
        const commonSuccessCallback = () => {
            message.success("操作成功!");
            isReloadData.value = true;
        };
        const commonFinallyCallback = () => {
            visible.value = false;
        };
        const commonErrorCallback = () => {
            message.error("操作失败!");
        };
        const commonJsx = (type: 1 | 2 | 3) => {
            let typeLable = "";
            let keywordRef = null;
            let ratioRef = null;
            if (type === 1) {
                typeLable = "主词";
                keywordRef = subject;
                ratioRef = subjectRatio;
            }
            if (type === 2) {
                typeLable = "长尾词";
                keywordRef = longTailedWord;
                ratioRef = longTailedWordRatio;
            }
            if (type === 3) {
                typeLable = "相关词";
                keywordRef = relatedWords;
                ratioRef = relatedWordsRatio;
            }
            return (
                <>
                    {keywordRef !== null && ratioRef !== null ? (
                        <>
                            <Divider style="height:30px">{typeLable}</Divider>
                            <Space align="start">
                                <Textarea
                                    placeholder={"输入 " + typeLable + " 多个换行"}
                                    v-model:value={keywordRef.value}
                                    style="margin-bottom:10px;width:240px"
                                ></Textarea>
                                <InputNumber
                                    style="width:100px"
                                    placeholder="最大密度"
                                    v-model:value={ratioRef.value}
                                    min={1}
                                    max={10}
                                ></InputNumber>
                            </Space>
                        </>
                    ) : (
                        <span></span>
                    )}
                </>
            );
        };
        return () => (
            <Modal v-model:open={visible.value} title={isAdd.value ? "添加" : "修改"} onOk={ok} style="width:440px">
                <br />
                选择网站
                <Select
                    show-search
                    v-model:value={pcDomain.value}
                    options={websiteOptions.value}
                    disabled={!isAdd.value}
                    onChange={onChange}
                    style="margin:0 0 15px 15px;width:200px"
                ></Select>
                {commonJsx(1)}
                {commonJsx(2)}
                {commonJsx(3)}
            </Modal>
        );
    }
});
